import { PureComponent } from "react"
import MForm from "./MForm"
import { connect } from "dva"
import md5 from "md5"
import { getParmaFromUrl, isNull, goTo, handleUrlParams, handleDataType, handleDateFunc, filterTemplate, goToPage, calcField, calcArr, isCheckPer, calcPermissionArr, checkPermission } from "../../utils/helper"
import { ActivityIndicator, Modal } from "antd-mobile"
import moment from 'moment';
import MLoading from '../Util/MLoading';
@connect(({ form, global }, { location }) => {
	let { pathname, search } = location;
	let formDataKey = md5(pathname + search);
	console.log(global.changeRefreshing, formDataKey)
	return ({
		fd: form[formDataKey] || {},
		formDataKey,
		queryLoading: global.queryLoading,
		isChangeRefreshing: global.changeRefreshing[formDataKey]
	})
})
export default class Edit extends PureComponent {
	constructor(props) {
		super(props);
		this.formRef = "";
		this.modal = null;
		this.enterTime = new Date().getTime();
		this.state = {
			showForm: false,
			paramsMsg: "",
			noLoading: false,
			info: {}
		}
	}
	componentWillReceiveProps1(next) {
		let { location: { search: search1 } } = next;
		let { location: { search: search2 } } = this.props;
		if (!_.isEqual(search1, search2)) {
			console.log("edit-search变化");
			this.enterTime = new Date().getTime();
			this.setState({
				showForm: false,
				paramsMsg: "",
				noLoading: false,
				info: {}
			});
			let { dispatch, formDataKey } = this.props;
			dispatch({
				type: "form/removeState",
				payload: {
					formDataKey
				}
			});
			setTimeout(() => {
				dispatch({
					type: "global/clearModal",
					payload: {}
				});
				this.loadConfig()
			})
		}
	}
	componentWillMount() {
		this.loadConfig()
	}
	loadConfig = (prop) => {
		let { isGoTo, refreshing } = prop || {};
		let { location, dispatch, formDataKey } = this.props;
		let { search, pathname, state = {}, hash } = location;
		if (!refreshing) {
			dispatch({
				type: "form/setState",
				payload: {
					[formDataKey]: {}
				}
			});
		}
		let params = getParmaFromUrl(search);
		const { _c = "", id = "", oid = "" } = params;
		if (isNull(_c)) {
			this.setState({
				paramsMsg: "缺少_c参数",
				reloadConfig: {
					reload: true,
					reloadFunc: this.loadConfig
				}
			})
		}
		else if (isNull(id) && isNull(oid)) {
			this.setState({
				paramsMsg: "缺少id参数",
				reloadConfig: {
					reload: true,
					reloadFunc: this.loadConfig
				}
			})
		}
		else {
			dispatch({
				type: "form/getFC",
				payload: {
					_c: _c,
					formDataKey: formDataKey,
					callback: (config) => {
						if (config.error) {
							let { code, msg } = config;
							this.setState({
								paramsMsg: <div><span>错误码:{code}</span> <span style={{ color: "#aaa" }}>{msg}</span></div>,
								reloadConfig: {
									reload: true,
									reloadFunc: this.loadConfig
								},
								noLoading: true
							})
						}
						else {
							let { navigate } = config;
							dispatch({
								type: "global/setNavigate",
								payload: {
									navigate,
									config,
									path: pathname + search
								}
							});

							let { api, fields } = config.data_store;
							let paramsDefault = handleUrlParams(fields, params);
							dispatch({
								type: "form/getInfo",
								payload: {
									apiInfo: api,
									data: params,
									callback: (info) => {
										let timeSub = new Date().getTime() - this.enterTime;
										let timeOut = 0;
										if (timeSub < 300) {
											timeOut = 300 - timeSub;
										}
										setTimeout(() => {
											this.setState({
												info: info,
												paramsDefault,
												showForm: true
											});
											let title = config.title;
											title = calcField(title, { ...paramsDefault, ...info });
											dispatch({
												type: "global/setHeaderTitle",
												payload: {
													title,
													path: pathname + search
												}
											});
											this.setState({
												empty: 1
											});
											if (isGoTo !== false) {
												// goTo(top)
											}
										}, timeOut)
									}
								}
							})
						}
					}
				}
			})
		}
	};
	componentDidMount() {

	}
	goUpdate = (e) => {
		let { fd } = this.props;
		let formData = fd.formData;
		this.setState({
			modalVisible: false,
			updateFormData: formData
		})
	};
	formSuccessFunc(result, isShowModal) {
		if (isShowModal !== false) {
			let { fd: { config } } = this.props;
			let { options = {} } = config;
			let { show_go_update, show_continue_add, cancel_label = "取消", close_label = "关闭", success_msg } = options;
			let buttons = [];
			if (cancel_label) {
				buttons.push(
					{ text: cancel_label, onPress: () => console.log('第2个按钮被点击了') }
				)
			}
			if (isNull(show_go_update) || show_go_update != 0) {
				buttons.push({ text: '继续修改', onPress: (e) => this.goUpdate(e) })
			}
			if (isNull(success_msg)) {
				success_msg = "操作成功，请继续操作"
			}
			this.modal = Modal.alert('', <div>{success_msg}</div>, buttons)
		}
	}
	handleSubmit = () => {
		let { fd: { config, formData }, dispatch } = this.props;
		let newFormData = handleDataType(config.data_store.fields, formData);
		const { actions } = config;
		let api = actions;
		let payload = {
			data: newFormData,
			apiInfo: api,
			isEditCreate: true,
			formSuccessFunc: this.formSuccessFunc.bind(this)
		};
		dispatch({
			type: "form/query",
			payload
		})
	};
	render() {
		let { showForm, paramsMsg, reloadConfig, paramsDefault, info, noLoading } = this.state;
		if (!showForm) {
			if (noLoading) {
				return (
					<MLoading  {...reloadConfig} />
				)
			}
			else {
				return (
					<div className="normal">
						<ActivityIndicator toast text="正在加载" animating={true} />
					</div>
				)
			}
		}
		let { formDataKey, fd = {}, dispatch, queryLoading, isModal, isChangeRefreshing } = this.props;
		let { config, formData = {} } = fd;
		const { fields } = config.data_store;
		let allFormData = {
			...paramsDefault,
			...info
		};
		let defaultFormData = {};
		fields.map(item => {
			let itemKey = item.name;
			let defVal = item.default_value;
			let isNumber = item.data_type === "number";
			if (isNull(item.default_value)) {
				defaultFormData[itemKey] = defVal
			}
			else {
				if (isNumber) {
					if (defVal.toString().indexOf("get") == -1) {
						defaultFormData[itemKey] = Number(defVal)
					}
					else {
						defVal = handleDateFunc(defVal);
						let { is_msec } = item;
						if (isNull(is_msec) || is_msec == 0) {
							defVal = parseInt(defVal / 1000);
						}
						defaultFormData[itemKey] = defVal;
					}
					//时间如果是number  默认到秒 is_msec默认是0
				}
				else if (isNull(item.data_type) || item.data_type === "string") {
					if (defVal.toString().indexOf("get") == -1) {
						defaultFormData[itemKey] = defVal + ""
					}
					else {
						defVal = handleDateFunc(defVal);
						defVal = moment(defVal).format("YYYY-MM-DD HH:mm")
						defaultFormData[itemKey] = defVal;
					}
				}
				else if (item.data_type === "array") {
					defaultFormData[itemKey] = defVal
				}
				else {
					defaultFormData[itemKey] = defVal
				}
			}
			if (allFormData[itemKey] !== undefined) {
				defaultFormData[itemKey] = allFormData[itemKey]
			}
		});
		fields.map(item => {
			let itemKey = item.name;
			let val = defaultFormData[item.field || item.name];
			if (item.data_type === "jsonobject" || item.data_type === "object") {
				//把a:{b:10} 格式转成 "a->b":10格式
				if (!isNull(val)) {
					if (item.data_type == "jsonobject") {
						val = JSON.parse(val);
					}
					function jsonToFormData(str, obj) {
						if (obj instanceof Object) {
							for (let i in obj) {
								jsonToFormData(str + "->" + i, obj[i])
							}
						}
						else {
							defaultFormData[str] = obj
						}
					}
					jsonToFormData(itemKey, val);
				}
				delete defaultFormData[itemKey]
			}
			else if (item.data_type == "hex") {
				let { config } = item;
				let obj = {};
				let len = 0;
				config.map((i, k) => {
					let { name, length, data_type } = i;
					let value = val.substring(len, len + length);
					if (data_type == "number") {
						value = Number(value);
					}
					defaultFormData[name] = value;
					len += length;
				})
				delete defaultFormData[itemKey];
				delete formData[itemKey]
			}
			else if (item.data_type === "jsonarray") {
				//数组字符串转成数组
				if (!isNull(val)) {
					defaultFormData[itemKey] = JSON.parse(val);
				}
			}
			else if (item.data_type === "array") {
				//不做处理
			}
		});
		let isShowFooterButton = true;
		let { widgets } = config;
		let { actions } = widgets;
		let footerBtn = [];
		if (isNull(actions)) {
			isShowFooterButton = false
		}
		else {
			for (let i in actions) {
				let item = { ...actions[i] };
				let { visible, disabled } = item;
				// visible = calcField(visible, formData);
				let _obj = {};
				let { permission_ctrl: _ctrl, permission_code: _code } = item;
				if (isCheckPer(_ctrl, _code) && calcPermissionArr.indexOf(_ctrl) != -1) {
					let per = checkPermission(_code);
					if (item[_ctrl] === undefined) {
						item[_ctrl] = per;
					}
					else {
						_obj[_ctrl] = per
					}
				}
				for (let i in item) {
					let val = item[i];
					if (calcArr.indexOf(i) != -1) {
						let isTrue = calcField(val, formData);
						if (calcPermissionArr.indexOf(i) !== -1) {
							isTrue = isTrue && (_obj[i] !== false);
						}
						item[i] = isTrue;
					}
				}
				if (item.visible === false || item.visible === "0" || item.visible === 0) {
					// console.log("visible为false");
				}
				else {
					// console.log("options",btn[0]);
					disabled = calcField(disabled, formData);
					disabled = disabled === true || disabled === "1" || disabled === 1;
					footerBtn.push({
						...item,
						disabled
					})
				}
			}
		}
		if (footerBtn.length == 0) {
			isShowFooterButton = false
		}
		let normalStyle = {};
		if (!isShowFooterButton) {
			normalStyle = {
				paddingBottom: 0
			}
		}
		if (isModal) {
			normalStyle = {
				...normalStyle,
				paddingTop: 0
			}
		}
		let formConfig = {
			isChangeRefreshing,
			loadConfig: this.loadConfig.bind(this),
			formDataKey,
			submitFunc: this.handleSubmit.bind(this),
			formSuccessFunc: this.formSuccessFunc.bind(this),
			config,
			isShowFooterButton,
			footerBtn,
			dispatch,
			defaultFormData,
			formData,
			fd,
			isModal,
			cancelFunc: () => {
				console.log("取消");
			},
			formRef: this.formRef
		};
		return (
			<div className="normal" style={{ ...normalStyle }} >
				{
					queryLoading && <ActivityIndicator toast text="" animating={true} />
				}
				<MForm ref={(e) => this.formRef = e} {...formConfig} location={this.props.location} />
			</div>
		)
	}
	componentWillUnmount() {
		if (this.modal) {
			this.modal.close()
		}
		let { dispatch, formDataKey } = this.props;
		dispatch({
			type: "form/removeState",
			payload: {
				formDataKey
			}
		})
	}
}